package org.microsites.util;

import org.directwebremoting.extend.AbstractCreator;
import org.directwebremoting.extend.Creator;
import org.directwebremoting.util.LocalUtil;

public class SpringDWRCreator extends AbstractCreator implements Creator {

  private String beanName = null;
  private Class<?> clazz = null;

  public Object getInstance() throws InstantiationException {
    try {
      return BeanFactory.get(beanName);
    }
    catch (RuntimeException re) {
      throw re;
    }
    catch (Exception ex) {
      throw new InstantiationException(ex.toString());
    }
  }

  /**
   * @return the beanName
   */
  public String getBeanName() {
    return beanName;
  }

  /**
   * @param beanName the beanName to set
   */
  public void setBeanName(String beanName) {
    this.beanName = beanName;
  }

  public void setClass(String classname) {
    try {
      this.clazz = LocalUtil.classForName(classname);
    }
    catch (ClassNotFoundException ex) {
      throw new IllegalArgumentException(ex);
    }
  }

  public Class<?> getType() {
    if (clazz == null) {
      try {
        clazz = getInstance().getClass();
      }
      catch (InstantiationException ex) {
        return Object.class;
      }
    }

    return clazz;
  }
}
